/*
 * Copyright 2010 Kevin L'Huillier <klhuillier@gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.lhuillier.pwsafe.io.codec;


import org.lhuillier.pwsafe.model.RawField;
import org.lhuillier.pwsafe.model.Record;
import org.lhuillier.pwsafe.model.RecordPwPolicy;
import com.google.inject.Inject;


/**
 * Reads and writes the encoded {@link RecordPwPolicy} string and returns 
 * a PasswordPolicy object.
 * <p>
 * <h4>From the official documentation:</h4>
 * <p>
 * <pre>
 * This field allows a specific Password Policy per entry. The format is:
 * "ffffnnnllluuudddsss" where:
 *
 *   ffff = 4 hexadecimal digits representing the following flags
 *     UseLowercase 0x8000 - can have a minimum length
 *     UseUppercase 0x4000 - can have a minimum length
 *     UseDigits 0x2000 - can have a minimum length
 *     UseSymbols 0x1000 - can have a minimum length
 *     UseHexDigits 0x0800 (if set, then no other flags can be set)
 *     UseEasyVision 0x0400
 *     MakePronounceable 0x0200
 *     Unused 0x01ff
 *
 *   nnn = 3 hexadecimal digits password total length
 *   lll = 3 hexadecimal digits password minimum number of lowercase characters
 *   uuu = 3 hexadecimal digits password minimum number of uppercase characters
 *   ddd = 3 hexadecimal digits password minimum number of digit characters
 *   sss = 3 hexadecimal digits password minimum number of symbol characters
 * </pre>
 */
class PwPolicyConverter implements FieldConverter {
    private static final byte TYPE_ID = 0x10;
    private final BinConverter binConv;
    
    @Inject
    PwPolicyConverter(BinConverter binConv) {
        this.binConv = binConv;
    }

    @Override
    public byte handledTypeId() {
        return TYPE_ID;
    }

    @Override
    public void toRecord(RawField raw, Record record) {
        String value = binConv.readString(raw.getValue());
        record.setPasswordPolicy(decode(value));
    }
    
    @Override
    public void toRaw(Record record, RawRecord raw) {
        RecordPwPolicy value = record.getPasswordPolicy();
        if (value != null) {
            String encoded = encode(value);
            raw.addField(new RawField(TYPE_ID, binConv.writeString(encoded)));
        }
    }
    
    RecordPwPolicy decode(String str) {
        RecordPwPolicy policy = new RecordPwPolicy();
        int flags = readHex(str, 0, 4);
        policy.setUseLowercase((flags & 0x8000) != 0);
        policy.setUseUppercase((flags & 0x4000) != 0);
        policy.setUseDigits((flags & 0x2000) != 0);
        policy.setUseSymbols((flags & 0x1000) != 0);
        policy.setUseHexDigits((flags & 0x0800) != 0);
        policy.setUseEasyVision((flags & 0x0400) != 0);
        policy.setMakePronounceable((flags & 0x0200) != 0);
        policy.setTotalLength(readHex(str, 4, 3));
        policy.setMinLowerLetters(readHex(str, 7, 3));
        policy.setMinUpperLetters(readHex(str, 10, 3));
        policy.setMinDigits(readHex(str, 13, 3));
        policy.setMinSymbols(readHex(str, 16, 3));
        return policy;
    }

    private int readHex(String str, int offset, int length) {
        return Integer.parseInt(str.substring(offset, offset + length), 16);
    }
    
    String encode(RecordPwPolicy policy) {
        int flags = 0;
        if (policy.getUseLowercase()) {
            flags += 0x8000;
        }
        if (policy.getUseUppercase()) {
            flags += 0x4000;
        }
        if (policy.getUseDigits()) {
            flags += 0x2000;
        }
        if (policy.getUseSymbols()) {
            flags += 0x1000;
        }
        if (policy.getUseEasyVision()) {
            flags += 0x0400;
        }
        if (policy.getMakePronounceable()) {
            flags += 0x0200;
        }
        // Hex digits overrides all other flags
        if (policy.getUseHexDigits()) {
            flags = 0x0800;
        }
        return String.format("%04x%03x%03x%03x%03x%03x", flags,
                policy.getTotalLength(), policy.getMinLowerLetters(),
                policy.getMinUpperLetters(), policy.getMinDigits(),
                policy.getMinSymbols());
    }
}
